from django.conf import settings
from fdfs_client.client import Fdfs_client, os
from rest_framework.decorators import action
from rest_framework.permissions import IsAdminUser
from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response
from goods.models import SPU, GoodsCategory, Brand
from meiduo_admin.serializers.skus import GoodsCategorySerializer
from meiduo_admin.serializers.spu import Spuserializers, Brandserializers

from meiduo_admin.utils import PageNumberPagination, PageNum


class SpuView(ModelViewSet):
    # 指定序列化器
    serializer_class = Spuserializers
    # 指定查询集
    queryset = SPU.objects.all()
    # 指定分页器
    pagination_class = PageNum
    # 认证
    permission_classes = [IsAdminUser]

    @action(methods=['post'], detail=False)
    def images(self, request):

        # 获取图片数据
        image = request.FILES['image']
        # 生成连接fastdfs对象
        client = Fdfs_client(os.path.join(settings.BASE_DIR, 'utils/fastdfs/client.conf'))

        # 以二进制数据上传
        res = client.upload_by_buffer(image.read())
        if res['Status'] != 'Upload successed.':
            return Response({'error':'上传失败'})
        # 获取链接
        image_path = res['Remote file_id']
        return Response({'img_url':'http://192.168.32.26:8888/'+image_path})

    def simple(self, request):
        # 获取品牌信息
        data = Brand.objects.all()
        ser = Brandserializers(data, many=True)
        return Response(ser.data)

    def categories(self, request):
        # 获取一级分类信息
        data = GoodsCategory.objects.filter(parent=None)

        ser = GoodsCategorySerializer(data, many=True)

        return Response(ser.data)

    def categoriesnum(self, request, pk):
        # 获取二三级分类信息
        data = GoodsCategory.objects.filter(parent=pk)

        ser = GoodsCategorySerializer(data, many=True)

        return Response(ser.data)


